var prefix = "/userAunt";
let myTimeNode = {}
let straIndex = 0
let EditVerify = []//审核时候的错误
let myMsg=null//关闭
let stra = () => {
    straIndex++;
    return `
<div style="margin-bottom: 10px;display: table;width: calc(100% - 50px);" class="newSet">
         <div class="layui-form-item formfixed">
			<div class="taskName col-sm-6" style="padding-left: 0">
				<input class="form-control startTime" type="text" placeholder="请输入工作开始时间"  mydata="${straIndex}">
			</div>
			<div class="taskScore col-sm-6" style="padding: 0">
				<input class="form-control endTime" type="text" placeholder="请输入工作结束时间" mydata="${straIndex}">
			</div>
				<div class="remove col-sm-2">删除</div>
		</div>
		<div class="taskDesc col-sm-12" style="padding: 0">
			<textarea name="description" class="form-control description" type="text" placeholder="请输入工作描述"></textarea>
		</div></div>`
};

let myTabId = []//保存前三的id
let switchData;

let myErrror = {
    lifePhoto: {
        title: '工作/生活照 最少上传6张最大上传12张',
        isTrue: true
    },
}
let myDataSkill=''

// 计算年龄的函数
function calculateAge(idCard) {
    // 提取身份证中的出生日期
    var birthDateStr = idCard.substring(6, 14); // 身份证号中出生日期的位置
    // 将出生日期字符串转换为日期对象
    var year = birthDateStr.substring(0, 4);
    var month = birthDateStr.substring(4, 6);
    var day = birthDateStr.substring(6, 8);
    var birthDate = new Date(year + "-" + month + "-" + day);
    // 获取当前日期
    var currentDate = new Date();
    // 计算年龄
    var age = currentDate.getFullYear() - birthDate.getFullYear();
    var currentMonth = currentDate.getMonth() + 1;
    var currentDay = currentDate.getDate();
    if (currentMonth < parseInt(month) || (currentMonth == parseInt(month) && currentDay < parseInt(day))) {
        age--;
    }
    // 返回年龄
    return age;
}

function getConstellation(idCard) {
    // 获取生日信息，身份证号码中生日信息的格式通常是年份和月份+日期
    var birthdayStr = idCard.substring(6, 14);
    // 解析年份、月份和日期
    var year = parseInt(birthdayStr.substring(0, 4));
    var month = parseInt(birthdayStr.substring(4, 6));
    var day = parseInt(birthdayStr.substring(6, 8));

    // 根据生日信息确定星座
    var constellation = '';
    if ((month === 1 && day >= 20) || (month === 2 && day <= 18)) {
        constellation = '水瓶座';
    } else if ((month === 2 && day >= 19) || (month === 3 && day <= 20)) {
        constellation = '双鱼座';
    } else if ((month === 3 && day >= 21) || (month === 4 && day <= 19)) {
        constellation = '白羊座';
    } else if ((month === 4 && day >= 20) || (month === 5 && day <= 20)) {
        constellation = '金牛座';
    } else if ((month === 5 && day >= 21) || (month === 6 && day <= 21)) {
        constellation = '双子座';
    } else if ((month === 6 && day >= 22) || (month === 7 && day <= 22)) {
        constellation = '巨蟹座';
    } else if ((month === 7 && day >= 23) || (month === 8 && day <= 22)) {
        constellation = '狮子座';
    } else if ((month === 8 && day >= 23) || (month === 9 && day <= 22)) {
        constellation = '处女座';
    } else if ((month === 9 && day >= 23) || (month === 10 && day <= 23)) {
        constellation = '天秤座';
    } else if ((month === 10 && day >= 24) || (month === 11 && day <= 22)) {
        constellation = '天蝎座';
    } else if ((month === 11 && day >= 23) || (month === 12 && day <= 21)) {
        constellation = '射手座';
    } else if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) {
        constellation = '摩羯座';
    }

    return constellation;
}

function getZodiac(idCard) {
    // 身份证号码中出生年份的位置（假设是从第7位开始到第10位）
    var year = idCard.substring(6, 10);

    // 计算出生年份对应的生肖
    var zodiacs = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"];
    var startYear = 1900; // 开始的年份
    var index = (parseInt(year) - startYear) % 12; // 计算生肖在数组中的索引
    return zodiacs[index];
}

function validateBankCard(input) {
    if (/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(input.value)) {
        $('#age').val(calculateAge(input.value));
        $('#constellation').val(getConstellation(input.value));
        $('#zodiac').val(getZodiac(input.value));
    } else {
        $('#age').val()
        $('#constellation').val()
        $('#zodiac').val()
    }
    layui.form.render('select');
}

//设置
const setMyWorkExperience = () => {
    let time = []
    for (let i = 0; i < (Object.keys(myTimeNode).length / 2); i++) {
        let item = $("input[mydata='" + i + "']")
        time.push({
            s: $(item[0]).val(),
            e: $(item[1]).val()
        })
    }
    let mydata = 0, dataNumber = 1, isShow = false;
    //计算时间
    for (let i = 0; i < time.length; i++) {
        let item = time[i]
        if ('' != item.s && '' != item.e) {
            isShow = true;
            var dayDiff = (new Date(item.e).getTime() - new Date(item.s).getTime()) / (1000 * 60 * 60 * 24);
            mydata += Number(dayDiff)
        }
    }
    //按照365算
    if (mydata > 365) {
        dataNumber = Math.floor(mydata / 365)
    }
    if (isShow) {
        $('#workExperience').val(dataNumber)
    } else {
        $('#workExperience').val('')
    }
}


$("#addList").click(function () {
    $("#addBox").append(stra);
    layui.use(['laydate'], function () {
        let laydate = layui.laydate;
        lay('.startTime').each(function () {
            //不存在加入
            if (!Object.keys(myTimeNode).includes('startTime' + $(this).attr('mydata'))) {
                myTimeNode['startTime' + $(this).attr('mydata')] = laydate.render({
                    elem: this,
                    trigger: 'click',
                    done: (value, dates) => {
                        myTimeNode['endTime' + $(this).attr('mydata')].config.min = {
                            year: dates.year,
                            month: dates.month - 1, //关键
                            date: dates.date,
                            hours: dates.hours,
                            minutes: dates.minutes,
                            seconds: dates.seconds
                        };
                        setMyWorkExperience()
                    }
                });
            }

        });
        lay('.endTime').each(function () {
            //不存在加入
            if (!Object.keys(myTimeNode).includes('endTime' + $(this).attr('mydata'))) {
                myTimeNode['endTime' + $(this).attr('mydata')] = laydate.render({
                    elem: this,
                    trigger: 'click',
                    done: (value, dates) => {
                        myTimeNode['startTime' + $(this).attr('mydata')].config.max = {
                            year: dates.year,
                            month: dates.month - 1,//关键
                            date: dates.date,
                            hours: dates.hours,
                            minutes: dates.minutes,
                            seconds: dates.seconds
                        }
                        setMyWorkExperience()
                    }
                });
            }
        });
    })
})

$("body").on('click', '.remove', function () {
    let myIndexNode = $(this).parents('.newSet').find("input[class='form-control startTime']").attr('mydata')
    delete myTimeNode['startTime' + myIndexNode]
    delete myTimeNode['endTime' + myIndexNode]
    $(this).parents('.newSet').remove();
})

layui.use(['form', 'xmSelect', 'upload', 'laydate'], function () {
    var form = layui.form;
    var layer = layui.layer, laydate = layui.laydate;
    var xmSelect = layui.xmSelect, upload = layui.upload;
    var loading;
    let datas = [];

    getSalaryList('#desireSalary',form)
    setWangeditor('#editor-consumerNotice','#toolbar-consumerNotice',$('#consumerNotice').val(),'请输入个人技能',function onchange(editor){
        myDataSkill = editor.getHtml()
    },null,$("#inputType").val() == 'infor')

    form.on('switch(switchTest)', function (data) {
        switchData = data
        $('#homeOrder').prop('disabled', !this.checked);
    })

    $.get('/js/webJs/jzweb/jazUserAunt/data.json', function (data) {
        let str = '';
        datas = data;
        data.map(function (v, k) {
            if (k == 0) str += `<option value="">请选择</option>`;
            str += `<option value="${v.name}" >${v.name}</option>`;
        })
        $("#province").html(str)
        form.render();
    })

    lay('.startTime').each(function () {
        myTimeNode['startTime' + $(this).attr('mydata')] = laydate.render({
            elem: this,
            trigger: 'click',
            max: "9999-12-31",
            done: (value, dates) => {
                myTimeNode['endTime' + $(this).attr('mydata')].config.min = {
                    year: dates.year,
                    month: dates.month - 1, //关键
                    date: dates.date,
                    hours: dates.hours,
                    minutes: dates.minutes,
                    seconds: dates.seconds
                };
                setMyWorkExperience()
            }
        });
    });
    lay('.endTime').each(function () {
        myTimeNode['endTime' + $(this).attr('mydata')] = laydate.render({
            elem: this,
            trigger: 'click',
            min: "1888-01-01",
            done: (value, dates) => {
                myTimeNode['startTime' + $(this).attr('mydata')].config.max = {
                    year: dates.year,
                    month: dates.month - 1,//关键
                    date: dates.date,
                    hours: dates.hours,
                    minutes: dates.minutes,
                    seconds: dates.seconds
                }
                setMyWorkExperience()
            }
        });
    });

    // laydate.render({
    //     elem: '#checkTime',
    //     trigger: 'click'
    // });


    form.on('select(province)', function (data) {
        let string = '';
        datas.map(function (v) {
            if (v.name == data.value) {
                v.city.map(function (val) {
                    string += `<option value="${val.name}" >${val.name}</option>`;
                })
            }
        })
        $("#city").html(string)
        form.render();
    });
    form.on('radio(demo-radio-filter)', function (data) {

        if (data?.elem?.value == '1') {
            $('#refuseReason').show()
        } else {
            $('#refuseReason').hide()
            $("textarea[name='refuseReason']").val('');
        }

    });
    form.on('select(city)', function (data) {
        let district = '';

        datas.map(function (v) {
            v.city.map(function (val) {
                if (val.name == data.value) {
                    val.area.map(function (item) {
                        district += `<option value="${item}" >${item}</option>`;
                    })
                }
            })
        })
        $("#district").html(district)
        form.render();
    });

    //同时绑定多个元素，并将属性设定在元素上
    upload.render({
        elem: '.uploadSend'
        , multiple: 'true'
        , before: function () {
            //阻止一下，
            // 最大数量
            let myDiv=$(this.elem[0]).attr('lay-data'),mydivList=[]
            //数据编辑
            myDiv=myDiv.replaceAll("{","")
            myDiv=myDiv.replaceAll("}","")
            mydivList=myDiv.split(',')
            myDiv={}
            mydivList.forEach(item=>{
                myDiv[item.split(':')[0]]=item.split(':')[1].replaceAll("'","")
            })
            let divName=myDiv.id
            let divValue=$("input[name='"+divName+"']").val()
            if(null!=divValue&&''!=divValue&&divValue.split(",").length>=myDiv.number){
                layer.msg('上传失败,已经达到最大数量');
                return false
            }
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res) {
            layer.close(loading);
            if (res.code == 0) {
                let that = this;
                changBackfill(res, that);
            } else {
                layer.msg('上传失败,请检查');
            }

        }
        , error: function (res) {
            layer.msg(res.msg)
        }
    })

    var type = xmSelect.render({
        el: '#type',
        name: 'type',
        layVerify: 'typeThod',
        max: 5,
        maxMethod(seles, item) {
            layer.msg('最大只能选择5个')
            //myTabId
        },
        data: [],
        on: function (data) {
            for (let i = 0; i < data.arr.length; i++) {
                if (myTabId.some(item => item.id === data.arr[i].value)) {
                    lay('.myIshowDiv').each(function () {
                        $(this).show();
                    });
                    return
                }
            }
            lay('.myIshowDiv').each(function () {
                if (switchData) {
                    // 设置开关状态为 false
                    switchData.elem.checked = false;
                }
                form.render('checkbox');
                $('#homeOrder').val('')
                $('#homeOrder').attr('disabled', true);
                $(this).hide();
            });
        }
    })
    var typevalue = $('#type').attr('value')
    var typedisabled = $('#type').attr('disabled') == 'disabled'
    typevalue = typevalue ? typevalue.split(',') : []
    // 服务类型
    AjaxGet(prefix + '/seleProject').then(function (response) {
        let str = [];
        let myResponseData = response.data
        // 对数组进行排序，按照 sort 属性值的大小升序排列
        myResponseData.sort((a, b) => a.sort - b.sort);
        myTabId = myResponseData.slice(0, 3)
        myResponseData.map(function (v) {
            str.push({
                name: v.name,
                value: v.id,
                selected: typevalue.includes(v.name),
                disabled: typedisabled
            })
        });
        type.update({
            data: str,
            autoRow: true,
        })
        //回显
        let myIshowDiv = false;
        for (let i = 0; i < typevalue.length; i++) {
            if (myTabId.some(item => item.name === typevalue[i])) {
                myIshowDiv = true
            }
        }
        if (myIshowDiv) {
            lay('.myIshowDiv').each(function () {
                $(this).show();
            });
        } else {
            lay('.myIshowDiv').each(function () {
                $(this).hide();
            });
        }
    }).catch(function (error) {
        layer.msg(error.msg)
    })

    // 人物标签
    var tips = xmSelect.render({
        el: '#tips',
        name: 'describe',
        layVerify: 'tips',
        max: 3,
        maxMethod(seles, item) {
            layer.msg('最大只能选择3个')
        },
        data: [],
    })
    var tipsvalue = $('#tips').attr('value')
    var tipsdisabled = $('#tips').attr('disabled')
    tipsvalue = tipsvalue ? tipsvalue.split(',') : []
    AjaxGet(prefix + '/seleLabel').then(function (response) {
        let str = [];
        response.data.map(function (v) {
            str.push({
                name: v.describe,
                value: v.id,
                selected: tipsvalue.includes(v.describe),
                disabled: tipsdisabled
            })
        });

        tips.update({
            data: str,
            autoRow: true,
        })

    }).catch(function (error) {
        layer.msg(error.msg)
    })

    //自定义验证规则
    form.verify({
        name: function (value, item) {
            if (null == value || value == '') {
                return '用户名不能为空';
            }
            if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                return '用户名不能有特殊字符';
            }
            if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                return '用户名首尾不能出现下划线\'_\'';
            }
            if (/^\d+\d+\d$/.test(value)) {
                return '用户名不能全为数字';
            }
        },
        phone: function (value) {
            if (value.length < 11) {
                const telStr = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
                if (!(telStr.test(value))) {
                    if ($('#inputType').val() == 'infor') {
                        if (EditVerify.indexOf('手机号码不规范') < 0) {
                            EditVerify.push('手机号码不规范')
                        }
                    } else {
                        return "手机号码输入不规范";
                    }
                } else {
                    if (EditVerify.indexOf('手机号码不规范') >= 0) {
                        EditVerify.splice(EditVerify.indexOf('手机号码不规范'), 1)
                    }
                }
            }
        },
        bankCard: function (value) {
            if (value.length > 0) {
                if (!/^\d{16,19}$/.test(value)) {
                    if ($('#inputType').val() == 'infor') {
                        if (EditVerify.indexOf('银行卡卡号不规范') < 0) {
                            EditVerify.push('银行卡卡号不规范')
                        }
                    } else {
                        return "银行卡卡号输入不规范";
                    }
                } else {
                    if (EditVerify.indexOf('银行卡卡号不规范') >= 0) {
                        EditVerify.splice(EditVerify.indexOf('银行卡卡号不规范'), 1)
                    }
                }
            }
        },
        idNumber: function (value) {
            if (value.length > 0) {

                if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
                    if ($('#inputType').val() == 'infor') {
                        if (EditVerify.indexOf('身份证号码不规范') < 0) {
                            EditVerify.push('身份证号码不规范')
                        }
                    } else {
                        return "身份证号码输入不规范";
                    }
                } else {
                    $('#age').val(calculateAge(value));
                    $('#constellation').val(getConstellation(value));
                    $('#zodiac').val(getZodiac(value));
                    layui.form.render('select');
                    if (EditVerify.indexOf('身份证号码不规范') >= 0) {
                        EditVerify.splice(EditVerify.indexOf('身份证号码不规范'), 1)
                    }
                }
            }
        },
    });

    //对数据进行回显
    myErrror.lifePhoto.isTrue = $('#lifePhotos').val() < 6
    if ($('#lifePhotos').val() == 0) {
        myErrror.lifePhoto.isTrue = false
    }

    //提交事件
    form.on('submit(submit)', function (data) {
        //图片限制判断
        if (!($('#inputType').val() == 'infor' && $('#inforType').val() == 'infor')) {
            //去除查看，上传回显的也要
            if (myErrror.lifePhoto.isTrue) {
                layer.msg(myErrror.lifePhoto.title);
                return false;
            }
        }

        //jazUserAuntDO 月嫂字段
        let params = {};
        params.jazUserAuntDO = {
            "phone": data.field.phone, // 电话
            "projectId": data.field.type, // 项目类型
            "labelId": data.field.describe, // 多选标签
            "introduction": data.field.introduction, // 自我介绍
            "residentHome": data.field.residentHome, // 是否驻家
            "desireSalary": data.field.desireSalary, // 工资
            "workExperience": data.field.workExperience, //  经验
            "skill": myDataSkill, // 个人技能
            "experience": data.field.experience, // 工作经历
            "inchPhoto": data.field.inchPhoto, // 寸照
            "idPhotoFront": data.field.idPhotoFront, // 身份证正面
            "idPhotoSide": data.field.idPhotoSide, // 身份证反面
            "lifePhoto": data.field.lifePhoto, // 工作/生活照
            "certificate": data.field.certificate, // 技能证书
            "report": data.field.report, // 体检报告
            "noCrime": data.field.noCrime, // 无犯罪证明
            // "checkTime": data.field.checkTime, // 体检日期
            "enableStatus": data.field.enableStatus ? 1 : 0,//是否启用
            "enableHome": data.field.enableHome ? 0 : 1 //首页展示
        };

        //userDO 用户字段
        params.userDO = {
            "name": data.field.name, //姓名
            "username": data.field.name,
            "orderPhone": data.field.phone, // 电话
            "mobile": data.field.phone,
            "nativePlace": data.field.nativePlace, // 籍贯
            "age": data.field.age, // 年龄
            "sex": data.field.sex, // 性别
            "zodiac": data.field.zodiac, // 生肖
            "constellation": data.field.constellation, // 星座
            "maritalStatus": data.field.maritalStatus, // 婚否
            "education": data.field.education, // 学历
            "height": data.field.height, // 身高
            "weight": data.field.weight, // 体重
            "detailedAddress": data.field.detailedAddress, // 现住址
            "idCardAddress": data.field.idCardAddress,//身份证地址
            "bankCard": data.field.bankCard,//银行卡卡号
            "openBank": data.field.openBank,//开户行
            "idNumber": data.field.idNumber,//身份证号
            "homeOrder": data.field.homeOrder,//首页优先级
            "referee": data.field.referee,//推荐人
        };
        let hours = [];
        $(".parseInset").find('.startTime').each(function (k, v) {
            hours.push({
                startTime: $(v).val(),
                endTime: $('.endTime').eq(k).val(),
                describe: $('.description').eq(k).val()
            })
        })

        params.jazUserAuntDO.experience = JSON.stringify(hours);
        if ($('#inputType').val() == 'add') {
            AjaxPost(prefix + '/insertAunt', params).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        } else if ($('#inputType').val() == 'edit') {
            params.jazUserAuntDO.id = $('#userId').val()
            params.userDO.id = $('#sysUserid').val()
            params.auditStatus=null== data.field.auditResult?null:1
            params.auditResult=parseInt(data.field.auditResult)
            params.showStatus=parseInt(data.field.auditResult)
            params.refuseReason=data.field.refuseReason
            if (null !== data.field.auditResult) {
                if (EditVerify.length > 0 && parseInt(data.field.auditResult) == 0) {
                    layer.msg('请拒绝，因为：' + EditVerify.join(','));
                    return false;
                }

                if (data.field.auditResult + "" == "1" && data.field.refuseReason == '') {
                    layer.msg("请输入拒绝原因")
                    return false
                }
            }
            AjaxPost(prefix + '/updateUserAnut', params).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        } else if ($('#inputType').val() == 'infor') {
            if ($('#inforType').val() == 'infor') {
                //设置审核
            //
            //     var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            //     parent.layer.close(index);
            //     parent.load();
            // } else if ($('#inforType').val() == 'edit') {


                if (null == data.field.auditResult) {
                    layer.msg('请选择审核状态');
                    return false;
                }
                if (EditVerify.length > 0 && parseInt(data.field.auditResult) == 0) {
                    layer.msg('请拒绝，因为：' + EditVerify.join(','));
                    return false;
                }

                if( data.field.auditResult+""=="1" && data.field.refuseReason==''){
                    layer.msg("请输入拒绝原因")
                    return false
                }

                AjaxPost('/userAunt/examineAunt', {
                    id: $('#userId').val(),
                    auditStatus: 1,
                    auditResult: parseInt(data.field.auditResult),
                    showStatus: parseInt(data.field.auditResult),
                    refuseReason: data.field.refuseReason
                }).then(function (response) {
                    parent.layer.msg("操作成功");
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);
                    parent.load();
                }).catch(error => {
                    layer.msg(error.msg)
                })


            }
        }

    });

});
let contrast = '',  // 寸照
    idPhotoFront = '', // 身份证正面
    idPhotoSide = '', // 身份证反面
    photo = $("#lifePhotos").val()>0?($("#lifePhotosString").val().split(",")):[],  // 工作/生活照
    certificate = $("#certificates").val()>0?($("#certificatesString").val().split(",")):[], // 技能证书
    report = $("#reports").val()!=''?($("#reports").val().split(",")):[], //体检报告
    noCrime = $("#noCrimes").val()!=''?($("#noCrimes").val().split(",")):[], //无犯罪证明
    str = '';
function changBackfill(res, obj) {

    // 添加图片之后展示在页面上
    if (obj.id == 'inchPhoto') {
        str = '';
        str = `
					<div class="layui-inline">
						<img class="upImg" onclick="photosClick()"src="${res.data}">
						<img class="closeUpload" src="/img/close.png" data-id="inchPhoto">
					</div>
				`;
        $("#" + obj.id).html(str);
        $("input[name='inchPhoto']").val(res.data);
    }

    if (obj.id == 'idPhotoFront') {
        str = '';
        str += `
				<div class="layui-inline">
					<img class="upImg" onclick="photosClick()"src="${res.data}">
					<img class="closeUpload" src="/img/close.png" data-id="idPhotoFront">
				</div>
			`;
        $("#" + obj.id).html(str);
        $("input[name='idPhotoFront']").val(res.data);
    }


    if (obj.id == 'idPhotoSide') {
        str = '';
        str += `
				<div class="layui-inline">
					<img class="upImg" onclick="photosClick()"src="${res.data}">
					<img class="closeUpload" src="/img/close.png" data-id="idPhotoSide">
				</div>
			`;
        $("#" + obj.id).html(str);
        $("input[name='idPhotoSide']").val(res.data);
    }

    if (obj.id == 'lifePhoto') {
        str = '';
        if (photo.length < obj.number) {
            photo.push(res.data);
            photo.forEach(function (v, k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" onclick="photosClick()"src="${v}">
						<img class="closeUpload" data-index="${k}" src="/img/close.png"  data-id="lifePhoto">
					</div>
				`;
            })
            $("#" + obj.id).html(str);
            $("input[name='lifePhoto']").val(photo.join(','));
            if (photo.length < obj.min) {
                // myMsg=layer.msg('上传的图片最少要' + obj.min + "张,目前有" + photo.length + "张")
                // myErrror.lifePhoto.isTrue = true
            } else {
                if(myMsg){layer.close(myMsg)}
                myErrror.lifePhoto.isTrue = false
            }
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    if (obj.id == 'certificate') {
        str = '';
        if (certificate.length < obj.number) {
            certificate.push(res.data);
            certificate.forEach(function (v, k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" onclick="photosClick()"src="${v}">
						<img class="closeUpload" data-index="${k}" src="/img/close.png" data-id="certificate">
					</div>
				`;
            })
            $("#" + obj.id).html(str);
            $("input[name='certificate']").val(certificate.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    if (obj.id == 'report') {
        str = '';
        if (report.length < obj.number) {
            report.push(res.data);
            report.forEach(function (v, k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" onclick="photosClick()"src="${v}">
						<img class="closeUpload" data-index="${k}" src="/img/close.png" data-id="report">
					</div>
				`;
            })
            $("#" + obj.id).html(str);
            $("input[name='report']").val(report.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    if (obj.id == 'noCrime') {
        str = '';
        if (noCrime.length < obj.number) {
            noCrime.push(res.data);
            noCrime.forEach(function (v, k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" onclick="photosClick()"src="${v}">
						<img class="closeUpload" data-index="${k}" src="/img/close.png" data-id="noCrime">
					</div>
				`;
            })
            $("#" + obj.id).html(str);
            $("input[name='noCrime']").val(noCrime.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    closeUpload();
}

closeUpload();

function closeUpload() {

    // 删除图片
    $(".closeUpload").unbind("click");
    $(".closeUpload").click(function () {

        $(this).parents('.layui-inline').remove();
        let objId = $(this).attr('data-id');
        console.log(objId,$(this).attr('data-index'))
        if (objId == 'inchPhoto') {
            $("input[name='inchPhoto']").val('');
        }

        if (objId == 'idPhotoFront') {
            $("input[name='idPhotoFront']").val('');
        }

        if (objId == 'idPhotoSide') {
            $("input[name='idPhotoSide']").val('');
        }

        if (objId == 'lifePhoto') {
            photo.splice($(this).attr('data-index'), 1);
            $("input[name='lifePhoto']").val(photo.join(','));
            //要根据下标改data-index的值
            let myImgList=$("img[data-id='lifePhoto']")
            for (let i = 0; i < myImgList.length; i++) {
                $(myImgList[i]).attr('data-index',i)
            }
        }

        if (objId == 'certificate') {
            certificate.splice($(this).attr('data-index'), 1);
            $("input[name='certificate']").val(certificate.join(','));
            //要根据下标改data-index的值
            let myImgList=$("img[data-id='certificate']")
            for (let i = 0; i < myImgList.length; i++) {
                $(myImgList[i]).attr('data-index',i)
            }
        }

        if (objId == 'report') {
            report.splice($(this).attr('data-index'), 1);
            $("input[name='report']").val(report.join(','));
            //要根据下标改data-index的值
            let myImgList=$("img[data-id='report']")
            for (let i = 0; i < myImgList.length; i++) {
                $(myImgList[i]).attr('data-index',i)
            }
        }

        if (objId == 'noCrime') {
            noCrime.splice($(this).attr('data-index'), 1);
            $("input[name='noCrime']").val(noCrime.join(','));
            //要根据下标改data-index的值
            let myImgList=$("img[data-id='noCrime']")
            for (let i = 0; i < myImgList.length; i++) {
                $(myImgList[i]).attr('data-index',i)
            }
        }

    })

}
